
const mongoose = require('mongoose');
var express = require('express')
// 注意这里的声明
var users = express()

const {createResponse}= require("../../util/createResponse/index");
const {businessCodes}= require("../../code/businessCodes/index");
const { userService } = require('../../service/impl/userService/userService');
const { role_service } = require('../../service/impl/role_service/index')
const {userRolesService} = require('../../service/impl/userRolesService/index');
const {userProfessionService} = require('../../service/impl/userProfessionService/index');
const { userBean, locationProfession } = require('../../beans/beansEnter');
const { userRolesBean } = require('../../beans/impl/userRolesBean');
const { role_code } = require('../../code/role_code/index');
const jwt = require('../../util/token/jwt');
const redis = require('../../util/redis/redis');

/* 管理员注册 */
/* 注册 */
users.post('/post/api/admin/registry', async (req,res) => {

  let uu
  try {

    uu  = await  userService.getIns().create({'ussername':req.body.username,'password':req.body.password})
  } catch (error) {
    console.log(error);
    createResponse(res,500,businessCodes.b2)
    return
  }
  createResponse(res,200,businessCodes.b7,uu)
  })



/* 注册 -
普通用户
*/
users.post('/post/api/user/registry', async (req,res) => {
  let news={}
  let uu
  try {
    news.username=req.body.username
    news.password= req.body.password
    uu  = await  userService.getIns().create(news)
  } catch (error) {
    console.log(error);
    createResponse(res,500,businessCodes.b2)
    return
  }
			if('_id' in uu){
                let resdata = new userBean()
               
                // 角色和权限bean
                let aa =  new userRolesBean()
                // 用户职业bean
                let userPro_bean = new locationProfession()
                let oo={}
                aa.userID = uu._id
                // 查找应用普通用户的角色ID
                let role001
                
                
                try {
                  // 查找普通用户角色的_id
                  role001  =  await role_service.getIns().findOne({"roleName_str":'普通用户'})
                  aa.appRoles_arr={}
                  aa.appRoles_arr.roleID = role001._id
                } catch (error) {
                  console.log(error);
                  createResponse(res,500,businessCodes.b2)
                  return
                }
               
     
                let ii
                
                try {
                  userPro_bean.userid = uu._id
                        // 角色和权限信息初始化
                   ii =    await userRolesService.getIns().create(aa)
                          // 职业信息初始化
                     await userProfessionService.getIns().create(userPro_bean)
                } catch (error) {
                  console.log(error);
                  createResponse(res,500,businessCodes.b2)
                  return
                }
                            resdata.uid = uu._id
                            resdata.username = uu.username
                            resdata.appRoles_arr = ii.appRoles_arr
                            resdata.companyRoles_arr = ii.companyRoles_arr
                            resdata.appDynamicsAuths_arr = ii.companyDynamicsAuths_arr
                            resdata.companyDynamicsAuths_arr = ii.companyDynamicsAuths_arr   
                            createResponse(res,200,businessCodes.b7,resdata)             
			}else{
        createResponse(res,200,businessCodes.b4)
			}
  })

  
  /* genju id查找并修改用户 */
  users.post('/post/api/user/updateuser', async (req,res) => {
    let result
    try {
      let id =req.body.conditions.id
      let updates = req.body.updates
      result =  await userService.getIns().findByIdAndUpdate(id,updates)
    } catch (error) {
      console.log(error);
      createResponse(res,500,businessCodes.b2)
      return
    }
    createResponse(res,200,businessCodes.b1,result)
  })
  /* 用户登录 */
  users.post('/post/api/user/login', async (req,res) => {
    console.log(req.body,'已接收')
    let conditions={}
    let hahares
    try {
      conditions.username = req.body.conditions.username
      conditions.password = req.body.conditions.password
      hahares   = await  userService.getIns().findOne(conditions)
    } catch (error) {
      console.log(error);
      createResponse(res,500,businessCodes.b2)
      return
    }
  
     if(JSON.stringify(hahares)!='{}'&&hahares!=undefined&&hahares!=null){
   
                     /* 查询到的账号ID作为token参数 */
                     let uid = hahares._id.toString();
                     /* 生成token */
                      let token = jwt.generateToken(uid);
                     /* 把生成的token保存到redis种 */
                     /* 86400 秒 为1天 */
                     try {
                      await redis.set(token, JSON.stringify({"id":uid}), '86400', function(err,result){
                        if (err) {
                        console.log(err);
                        return;
                        }else{
                        console.log('保存redis成功:');}
                    })
                     } catch (error) {
                      console.log(error);
                      createResponse(res,500,businessCodes.b2)
                      return
                     }
                    
                      
              
                     let bb  //用户角色权限信息 
                     let conditions={
                                     "userID":uid
                                     }
                     let fills = {
                             "key1":{
                                 "path":"appRoles_arr.roleID",
                                 "populate": {
                                     "path": "roleAuths_arr.auth_ref"
                                   }
                             }
                         }
                         try {
                          bb  =   await  userRolesService.getIns().findOne(conditions,null,fills)
                         } catch (error) {
                          console.log(error);
                          createResponse(res,500,businessCodes.b2)
                          return
                         }
                      //   用户职业信息  

 
                 
                      
             
                     let resdata= new userBean()
                     resdata.userToken=token
                     resdata.uid=uid
                     resdata.username=hahares?.username
                     resdata.resumeInfo=hahares?.resumeInfo
                     
                     // 应用角色
                     resdata.appRoles_arr = bb?.appRoles_arr
                     // 应用动态权限
                     resdata.appDynamicsAuths_arr = bb?.appDynamicsAuths_arr  
                     resdata.companyRoles_arr = bb?.companyRoles_arr
                     resdata.companyDynamicsAuths_arr = bb?.companyDynamicsAuths_arr
                     createResponse(res,200,businessCodes.b5,resdata)
                    }else{
                      createResponse(res,200,businessCodes.b6)
                      return
                    }
     
  })


    /* 管理员登录 */
    users.post('/post/api/admin/login', async (req,res) => {
      // 这是创建的临时变量,目的存储对象
      let conditions={}
      // 这是用来存储数据库结果,返回给前端的
      let hahares
      try {
        
        conditions.username = req.body.username
        conditions.password = req.body.password
        hahares   = await  userService.getIns().findOne(conditions)
      } catch (error) {
        console.log(error);
        createResponse(res,500,businessCodes.b2)
        return
      }
    
       if(JSON.stringify(hahares)!='{}'&&hahares!=undefined&&hahares!=null){
     
                       /* 查询到的账号ID作为token参数 */
                       let uid = hahares._id.toString();
                       /* 生成token */
                        let token = jwt.generateToken(uid);
                       /* 把生成的token保存到redis种 */
                       /* 86400 秒 为1天 */
                       try {
                        await redis.set(token, JSON.stringify({"id":uid}), '86400', function(err,result){
                          if (err) {
                          console.log(err);
                          return;
                          }else{
                          console.log('保存redis成功:');}
                      })
                       } catch (error) {
                        console.log(error);
                        createResponse(res,500,businessCodes.b2)
                        return
                       }
                      
                        
                
                       let bb  //用户角色权限信息 
                       let conditions={
                                       "userID":uid
                                       }
                       let fills = {
                               "key1":{
                                   "path":"appRoles_arr.roleID",
                                   "populate": {
                                       "path": "roleAuths_arr.auth_ref"
                                     }
                               }
                           }
                           try {
                            bb  =   await  userRolesService.getIns().findOne(conditions,null,fills)
                           } catch (error) {
                            console.log(error);
                            createResponse(res,500,businessCodes.b2)
                            return
                           }
                        //   用户职业信息  
  
   
                   
              
               
                       let resdata= new userBean()
                       resdata.token=token
                       resdata.uid=uid
                       resdata.username=hahares?.username
                       // 应用角色
                       resdata.appRoles_arr = bb?.appRoles_arr
                       // 应用动态权限
                       resdata.appDynamicsAuths_arr = bb?.appDynamicsAuths_arr  
                       resdata.companyRoles_arr = bb?.companyRoles_arr
                       resdata.companyDynamicsAuths_arr = bb?.companyDynamicsAuths_arr
                       createResponse(res,200,businessCodes.b5,resdata)
                      }else{
                        createResponse(res,200,businessCodes.b6)
                        return
                      }
       
    })


  // 查找所有用户
  users.post('/post/api/user/queryUsers', async (req,res) => {
    let result
    try {
      result =  await userService.getIns().find()
    } catch (error) {
      console.log(error);
      createResponse(res,500,businessCodes.b2)
      return
    }
    createResponse(res,200,businessCodes.b1,result)
  })


    // 根据用户id查找单个用户的信息
    users.post('/post/api/user/queryOneUser', async (req,res) => {
      let result
      try {
        let conditions = req.body.conditions
        result =  await userService.getIns().findOne(conditions)
      } catch (error) {
        console.log(error);
        createResponse(res,500,businessCodes.b2)
        return
      }
      createResponse(res,200,businessCodes.b1,result)
    })

  /* 
  根据id删除用户
  */
  users.post('/post/api/user/deleteUsers', async (req,res) => {
    let result
    let id
    try {
      id = req.body.conditions.id
      result =  await userService.getIns().findByIdAndDelete(id)
      // 删除该用户的角色与权限信息
       await userRolesService.getIns().findOneAndDelete({"userID":id})
    } catch (error) {
      console.log(error);
      createResponse(res,500,businessCodes.b2)
      return
    }
    createResponse(res,200,businessCodes.b1,result)

  })
  
  
  
  
 

  
  
  //#endregion

  module.exports= users